package com.ruoyi.system.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author: zhoupeng
 * @date: 2021/9/23 22:39
 * @descreption: 文件预览控制层
 */
@Slf4j
@Controller
public class PreviewController {

    @Value("${file.download.dir}")
    private String realPath;

    @Value("${ftpIp}")
    private String ftpIp;

    @Value("${ftpPort}")
    private int ftpPort;

    @Value("${ftpUserName}")
    private String ftpUserName;

    @Value("${ftpPassword}")
    private String ftpPassword;

    @Value("${ftpFilePath}")
    private String ftpFilePath;

    @Value("${pdfFilePath}")
    private String pdfFilePath;

    @Autowired
    private DocumentConverter converter;

    @ResponseBody
    @RequestMapping("preview")
    public void toPdfFile(HttpServletRequest request, HttpServletResponse response, String fileName) {
        StringBuffer url = request.getRequestURL();
        log.info("请求url: " + url);
        if (url.toString().contains(ftpIp)) {
            File file = new File(realPath + fileName);
            try {
                File newFile = new File(pdfFilePath);
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                String newFileMix = pdfFilePath + "JCccc" + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6) + ".pdf";
                converter.convert(file).to(new File(newFileMix)).execute();
                ServletOutputStream outputStream = response.getOutputStream();
                InputStream in = new FileInputStream(newFileMix);
                int i = IOUtils.copy(in, outputStream);
                in.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            FTPClient ftpClient = new FTPClient();
            InputStream inputStream = null;
            try {
                ftpClient.connect(ftpIp, ftpPort);
                ftpClient.login(ftpUserName, ftpPassword);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                int reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }
                String ftpPath = "ftp://" + ftpUserName + ":" + ftpPassword + "@" + ftpIp + ":" + ftpPort + "/";
                log.info("ftp地址: " + ftpPath);
                FTPFile[] fs = ftpClient.listFiles();
                log.info("文件数量: " + fs.length);
                String remoteFileName;
                OutputStream os;
                boolean flag = false;
                for (FTPFile ff : fs) {
                    byte[] bytes = ff.getName().getBytes("iso-8859-1");
                    remoteFileName = new String(bytes, "gbk");
                    if (fileName.equals(remoteFileName)) {
                        File newFile = new File(ftpFilePath);
                        if (!newFile.exists()) {
                            log.info("新建: " + pdfFilePath);
                            newFile.mkdirs();
                        }
                        File localFile = new File(ftpFilePath + fileName);
                        log.info("本地路径: " + localFile);
                        os = new FileOutputStream(localFile);
                        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                        flag = ftpClient.retrieveFile(ff.getName(), os);
                        break;
                    }
                }
                if (flag) {
                    File file = new File(ftpFilePath + fileName);
                    try {
                        File newFile = new File(pdfFilePath);
                        if (!newFile.exists()) {
                            log.info("新建目录: " + pdfFilePath);
                            newFile.mkdirs();
                        }
                        String saveName = "JCccc" + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6);
                        String fileType = ".pdf";
                        String newFileMix = pdfFilePath + saveName + fileType;
                        converter.convert(file).to(new File(newFileMix)).execute();
                        ServletOutputStream outputStream = response.getOutputStream();
                        InputStream in = new FileInputStream(newFileMix);
                        int i = IOUtils.copy(in, outputStream);
                        in.close();
                        outputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (ftpClient.isConnected()) {
                    try {
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @RequestMapping("getDiagram/{fileName}")
    public void getDiagram(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName) {
        log.info("fileName: " + fileName);
        File localFile=new File(ftpFilePath+"Graph"+File.separator + fileName);;

        ServletOutputStream out = null;
        FileInputStream ips = null;
        FTPClient ftpClient =null;
        OutputStream os = null;
        try {
            StringBuffer url = request.getRequestURL();
            boolean flag = false;
            log.info("请求url: " + url);
            if (url.toString().contains(ftpIp)) {
                localFile= new File(realPath+"Graph"+File.separator  + fileName);
                flag=true;
            }else{
                ftpClient = new FTPClient();
                ftpClient.connect(ftpIp, ftpPort);
                ftpClient.login(ftpUserName, ftpPassword);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                int reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }
                String ftpPath = "ftp://" + ftpUserName + ":" + ftpPassword + "@" + ftpIp + ":" + ftpPort + "/";
                log.info("ftp地址: " + ftpPath);
                boolean changeDirectory=ftpClient.changeWorkingDirectory("Graph");
                log.info("ftp修改地址: " + changeDirectory+">>");
                FTPFile[] fs = ftpClient.listFiles();
                log.info("文件数量: " + fs.length);
                String remoteFileName;

                flag = false;
                for (FTPFile ff : fs) {
                    byte[] bytes = ff.getName().getBytes("iso-8859-1");
                    remoteFileName = new String(bytes, "gbk");
                    if (fileName.equals(remoteFileName)) {
                        File newFile = new File(ftpFilePath+"Graph"+File.separator);
                        if (!newFile.exists()) {
                            log.info("新建: " + ftpFilePath+"Graph"+File.separator);
                            newFile.mkdirs();
                        }
                        localFile = new File(ftpFilePath+"Graph"+File.separator + fileName);
                        log.info("本地路径: " + localFile);
                        os = new FileOutputStream(localFile);
                        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                        flag = ftpClient.retrieveFile(ff.getName(), os);
                        break;
                    }
                }
                if(null !=os){
                    os.close();
                }
            }

            if (flag) {
                try {
                    response.setContentType("multipart/form-data");
                    ServletOutputStream outputStream = response.getOutputStream();
                    ips = new FileInputStream(localFile);
                    int i = IOUtils.copy(ips, outputStream);
                    ips.close();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(null !=ftpClient){
                if (ftpClient.isConnected()) {
                    try {
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null !=ips){
                try {
                    ips.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @ResponseBody
    @RequestMapping("viewFileInfo/{fileType}/{fileName}")
    public void viewFileInfo(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileType, @PathVariable String fileName) {
        StringBuffer url = request.getRequestURL();
        String pdfFilePath_new=pdfFilePath+fileType+File.separator;
        String realPath_new=realPath+fileType+File.separator;
        String ftpFilePath_new=ftpFilePath+fileType+File.separator;
        log.info("请求url: " + url);
        if (url.toString().contains(ftpIp)) {
            File file = new File(realPath_new + fileName);
            try {
                File newFile = new File(pdfFilePath_new);
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                log.info("newFile>>getPath: " + newFile.getPath());
                String newFileMix = pdfFilePath_new + "JCccc" + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6) + ".pdf";
                converter.convert(file).to(new File(newFileMix)).execute();
                ServletOutputStream outputStream = response.getOutputStream();
                InputStream in = new FileInputStream(newFileMix);
                log.info("newFileMix>>url: " + newFileMix);
                int i = IOUtils.copy(in, outputStream);
                in.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            FTPClient ftpClient = new FTPClient();
            InputStream inputStream = null;
            try {
                ftpClient.connect(ftpIp, ftpPort);
                ftpClient.login(ftpUserName, ftpPassword);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                int reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }
                String ftpPath = "ftp://" + ftpUserName + ":" + ftpPassword + "@" + ftpIp + ":" + ftpPort + "/";
                log.info("ftp地址: " + ftpPath);
                boolean changeDirectory=ftpClient.changeWorkingDirectory(fileType);
                log.info("ftp修改地址: " + changeDirectory+">>");
                FTPFile[] fs = ftpClient.listFiles();
                log.info("文件数量: " + fs.length);
                String remoteFileName;
                OutputStream os;
                boolean flag = false;
                for (FTPFile ff : fs) {
                    byte[] bytes = ff.getName().getBytes("iso-8859-1");
                    remoteFileName = new String(bytes, "gbk");
                    if (fileName.equals(remoteFileName)) {
                        File newFile = new File(ftpFilePath_new);
                        if (!newFile.exists()) {
                            log.info("新建: " + pdfFilePath_new);
                            newFile.mkdirs();
                        }
                        File localFile = new File(ftpFilePath_new + fileName);
                        log.info("本地路径: " + localFile);
                        os = new FileOutputStream(localFile);
                        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                        flag = ftpClient.retrieveFile(ff.getName(), os);
                        break;
                    }
                }
                if (flag) {
                    File file = new File(ftpFilePath_new + fileName);
                    try {
                        File newFile = new File(pdfFilePath_new);
                        if (!newFile.exists()) {
                            log.info("新建目录: " + pdfFilePath_new);
                            newFile.mkdirs();
                        }
                        String saveName = "JCccc" + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6);
                        String newFileMix = pdfFilePath_new + saveName + ".pdf";
                        converter.convert(file).to(new File(newFileMix)).execute();
                        ServletOutputStream outputStream = response.getOutputStream();
                        log.info("saveName>>url: " + saveName);
                        InputStream in = new FileInputStream(newFileMix);
                        int i = IOUtils.copy(in, outputStream);
                        in.close();
                        outputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (ftpClient.isConnected()) {
                    try {
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

}
